<template>
  <transition name="down">
    <div
      v-show="isVisable"
      class="min-w-[420px] fixed top-[50px] left-[50%] translate-x-[-50%] z-50 flex items-center px-3 py-1.5 rounded-sm border cursor-pointer"
      :class="styles[type].containerClass"
    >
      <m-svg-icon
        :name="styles[type].icon"
        :fillClass="styles[type].fillClass"
        class="h-1.5 w-1.5 mr-1.5"
      />
      <span class="text-sm" :class="styles[type].textClass">{{ content }}</span>
    </div>
  </transition>
</template>

<script>
const SUCCESS = 'success'
const WARN = 'warn'
const ERROR = 'error'
const INFO = 'info'

const typeEnum = [INFO, SUCCESS, WARN, ERROR]
</script>

<script setup>
import { onMounted, ref } from 'vue'
import mSvgIcon from '../svg-icon/index.vue'

const props = defineProps({
  /**
   * message 的消息类型
   */
  type: {
    type: String,
    required: true,
    validator(val) {
      const result = typeEnum.includes(val)
      if (!result) {
        throw new Error(`你的  type 必须是 ${typeEnum.join('、')} 中的一个`)
      }
      return result
    },
  },
  // 展示时长
  duration: {
    type: Number
  },
  // 关闭回调
  destory: {
    type: Function
  },
  // 描述文本
  content: {
    type: String,
    required: true
  }
})

/**
 * 样式表数据
 */
const styles = {
  // 消息提示
  info: {
    icon: 'info',
    fillClass: 'fill-info-100',
    textClass: 'text-info-100',
    containerClass: 'bg-info-300 border-info-200 hover:shadow-lg hover:shadow-info-300'
  },
  // 警告
  warn: {
    icon: 'warn',
    fillClass: 'fill-warn-100',
    textClass: 'text-warn-100',
    containerClass: 'bg-warn-300 border-warn-200 hover:shadow-lg hover:shadow-warn-300'
  },
  // 成功
  success: {
    icon: 'success',
    fillClass: 'fill-success-100',
    textClass: 'text-success-100',
    containerClass: 'bg-success-300 border-success-200 hover:shadow-lg hover:shadow-success-300'
  },
  // 错误
  error: {
    icon: 'error',
    fillClass: 'fill-error-100',
    textClass: 'text-error-100',
    containerClass: 'bg-error-300 border-error-200 hover:shadow-lg hover:shadow-error-300'
  }
}

// 是否展示
const isVisable = ref(false)

// 关闭动画执行时间
const animDuration = '0.5s'

/**
 * 为了保证动画展示，需要在 mounted 之后进行展示
 */
onMounted(() => {
  isVisable.value = true
  setTimeout(() => {
    isVisable.value = false
    setTimeout(() => {
      if (props.destory) {
        props.destory()
      }
    }, parseInt(animDuration.repeat('0.', '').repeat('s', '') * 100))
  }, props.duration)
})
</script>

<style lang="scss" scoped>
.down-enter-active,
.down-leave-active {
  transition: all v-bind(animDuration);
}

.down-enter-from,
.down-leave-to {
  opacity: 0;
  transform: translate3d(-50%, -100px, 0);
}
</style>
